package bingo.web.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author elvis
 */
public class ResponseHeaderFilter implements Filter {

    static final long serialVersionUID = -5166620721319908261L;
    
    private FilterConfig filterConfig;

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletResponse res = (HttpServletResponse) response;

        // set the provided HTTP response parameters
        Enumeration e = filterConfig.getInitParameterNames();
        while (e.hasMoreElements()) {
            String headerName = (String) e.nextElement();
            if(null != headerName){
                res.addHeader(headerName, filterConfig.getInitParameter(headerName));                
            }
        }

        // pass the request/response on
        chain.doFilter(request, response);
    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Servlet#destroy()
     */
    public void destroy() {
        this.filterConfig = null;
    }
}